<?php
namespace app\api\controller\datascreen;

use app\api\controller\Base;
use app\common\model\user\User as UserModel;
use app\common\model\company\Company;
use app\common\model\orderhawa\Hawa;
use app\common\model\orderhawa\HawaList;
use app\common\model\orderreceipt\Receipt;
use app\common\model\orderreceipt\ReceiptList;
use app\api\controller\mytool\Setting;
use think\facade\Request;
use Firebase\JWT\JWT;
use app\common\model\customer\Street;
use app\common\model\company\Contract;
use app\common\model\company\CompanyFile;
use app\common\model\customer\Customer as Customermodel;
use app\common\model\company\ContractDetails;
use app\common\model\orderdata\Goods;
use app\common\model\transit\Transport;
use app\api\controller\mytool\Mapapi;
class Regulatory extends Base
{
    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 获取统计的产废类别、数量、时间、去向、现有产废单位多少家
     * @return [type] [description]
     */
    public function sumdata(){
        $idata = input('post.');
        //获取每个区域现有产废单位多少家
            $data['streetinfo'] = Customermodel::group('StreetId');
            //街道数据
            if(!empty($idata['streeid'])){
                $data['streetinfo'] = $data['streetinfo']->where('StreetId','in',$idata['streeid']);
            }
            
            $data['streetinfo'] = $data['streetinfo']->column('count(StreetId) as StreetCount','StreetId');
            $streetid = [];
            foreach ($data['streetinfo'] as $key => $value) {
                if(!empty($key)){
                    $streetid[] = $key;
                }
            }
            //获取街道信息
            $streetinfo = Street::where('StreetId','in',$streetid)->select();
            foreach ($streetinfo as $key => $value) {
                $streetinfo[$key]['Count'] = $data['streetinfo'][$value['StreetId']];
            }
            $rdata['streetinfo'] = $streetinfo;

        //公用部分
        //获取单位列表
             //街道数据
            if(!empty($idata['streeid'])){
                $companyid = Customermodel::where('StreetId','in',$idata['streeid'])->column('CompanyId');
            }else{
                $companyid = Customermodel::column('CompanyId');
            }
            

        //此段时间中这些单位的合同中危废代码多少种/预计产废量多少
            //获取合同id
            $contractid = Contract::where('CompanyId','in',$companyid);
            //时间选择
            if(!empty($endtime) && !empty($startTime)){
                $contractid = $contractid->where('CreateTime','>=',$startTime);
                $contractid = $contractid->where('CreateTime','<=',$endtime);
            }
            $contractid = $contractid->column('ContractId');
            $contractinfo = ContractDetails::group('GoodId')->where('ContractId','in',$contractid)->field(['sum(EstimatedWeight) as SumEstimatedWeight','count(GoodId) as Count','GoodId'])->select();
            $contractgoodid = get_array_id($contractinfo,'GoodId');
            $contractinfo = arr_id_formate($contractinfo,'GoodId',true);

        //此段时间中订单中危废代码多少种/实际产废量多少
            //获取订单id
            $hawalistid = HawaList::where('CompanyId','in',$companyid);
            //时间选择
            if(!empty($endtime) && !empty($startTime)){
                $hawalistid = $hawalistid->where('UpTime','>=',$startTime);
                $hawalistid = $hawalistid->where('UpTime','<=',$endtime);
            }
            $hawalistid = $hawalistid->column('HawaListId');
            $hawalistinfo = Hawa::group('GoodId')->where('HawaListId','in',$hawalistid)->field(['sum(Weight) as SumWeight','count(HawaId) as Count','GoodId'])->select();
            $hawagoodid = get_array_id($hawalistinfo,'GoodId');
            $hawalistinfo = arr_id_formate($hawalistinfo,'GoodId',true);
        //汇总两边的goodid
        $goodid = array_merge($contractgoodid,$hawagoodid);        
        $goodid = array_unique($goodid);
        $goodlist = Goods::where('GoodId','in',$goodid)->hidden(['TotalWeight'])->select();
        foreach ($goodlist as $key => $value) {
            if(!empty($contractinfo[$value['GoodId']])){
                $goodlist[$key]['contract'] = $contractinfo[$value['GoodId']];
            }
            if(!empty($hawalistinfo[$value['GoodId']])){
                $goodlist[$key]['hawa'] = $hawalistinfo[$value['GoodId']];
            }
        }
        $rdata['goodlist'] = $goodlist;
        return myok($rdata);
    }

    /**
     * 获取街道数据
     * @return [type] [description]
     */
    public function getstreet(){
        $data = Street::getarray();
        return myok($data);
    }

    //客户列表：客户电话/客户名称搜索
    public function  getcustomerlist(){
        self::is_login();
        $key = trim(input('searchkey'));
        $endtime = input('end');
        $startTime = input('start');
        $customerwhere = input('customer_where');//客户筛选
        $time = input('time_where');//时间筛选


        if($key=="%"){return moerr('非法参数');}
        $idata = input('post.');
        //街道数据
        if(!empty($idata['streeid'])){
            $sdata['where'][] = ['StreetId','in',$idata['streeid']];
        }

        //定位
        if(!empty($idata['lat'])){
            $sdata['field'] = [str_distance($idata['lat'],$idata['lon'])];
            $sdata['order'] = 'distance asc';
            $sdata['where'][] = ['lat','<>','is NULL'];
        }

        //页码
        $pages  = input('pages');
        if(!empty($pages)){
            $sdata['pageindex'] = $pages;
        }

        //关键词
        if(!empty($key)){
            $sdata['where'][] = ['(Name like "%'.$key.'%")or(Address like "%'.$key.'%")or(UserName like "%'.$key.'%")or(UserTel like "%'.$key.'%")or(Tel like "%'.$key.'%")'];
        }

        //输出限制
        $limit  = input('limit');
        if(!empty($limit)){
            $sdata['p_limit'] = $limit;
        }else{
            $sdata['p_limit'] = 100;
        }

        //合同筛选
        if(!empty($customerwhere)){
            $today = date('Y-m-d H:i:s',time());
            $companyId = Contract::where('StartTime','<=',$today)->where('EndTime','>=',$today)->where('State',Contract::STATEOK)->column('CompanyId');
            switch ($customerwhere) {
                case 'cunzai'://存在生效的合同
                    $sdata['where'][] = ['CompanyId','in',$companyId];
                    break;
                case 'bucunzai'://不存在生效的合同
                    $sdata['where'][] = ['CompanyId not in ('.implode(',',$companyId).') or CompanyId is NULL'];
                    break;
            }
        }

        //时间选择
        if(!empty($endtime) && !empty($startTime)){
            $timefile = '';
            switch ($time) {
                case 'goutongshijian':
                    $customerId = Customervisit::where('VisitTime','>=',$startTime)->where('VisitTime','<=',$endtime.' 24:00')->column('CustomerId');
                    $sdata['where'][] = ['CustomerId','in',$customerId];
                    break;
                case 'tianjiashijian':
                    $sdata['where'][] = ['AddTime','>=',$startTime];
                    $sdata['where'][] = ['AddTime','<=',$endtime];
                    break;
                case 'hetongqianding':
                    $compnayId = Contract::where('SettlementTime','>=',$startTime)->where('SettlementTime','<=',$endtime.' 24:00')->column('CompanyId');
                    $sdata['where'][] = ['CompanyId','in',$compnayId];
                    break;
            }
        }
        
        //地图显示客户数据：
        //绿灯 存在生效的合同   黄灯（15天有跟进） 红灯（超过15天没跟进） 
        $sdata['Type'] = 'customer';
        $sb = Customermodel::usergetlist($sdata,'datascreen');
        $time = date('Y-m-d H:i:s',(time() - 30*24*60*60));
        foreach ($sb['list'] as $key => $value) {
            $sb['list'][$key]['statetext'] = $sb['statetext'][$value['State']];
            $sb['list'][$key]['guard_state_text'] = empty($value['guard_state'])?'':'保护中';
            $sb['list'][$key]['has_contract'] = empty($value['contractlist'])?false:true;
            $sb['list'][$key]['has_visit'] = $value['LastTime']>$time?true:false;
        }
        return myok($sb);
    }

    //获取客户信息
    public function getinfo(){
        self::is_login();
        $id = input('id');
        if(empty($id)){
            return myerr('缺少参数，请重新尝试');
        }
        $data = Customermodel::user_getinfo($id,'datascreen');
        if(empty($data)){
            return myerr('没有找到此客户');
        }
        if(!empty($data['CompanyId'])){
            $data['contract'] = Contract::getcompanycontractlist($data['CompanyId'],'datascreen_regulatory');
        }
        $data['url'] = WEBURL.'print/contract_rote?p=';
        return myok($data);
    }

    /**
     * 根据车量imei获取车辆及订单信息
     * @return [type] [description]
     */
    public function getcarinfo_imei(){
        self::is_login();
        $id = input('imei');
        if(empty($id)){
            return myerr('缺少参数，请重新尝试');
        }
        $carinfo = Transport::where('IMEI',$id)->find();
        if(empty($carinfo)){
            return myerr('没有找到您需要的车辆');
        }
        $data['carinfo'] = $carinfo;
        $orderwhere['where'][] = ['State','>=',HawaList::STATETRANSPORT];
        $orderwhere['where'][] = ['TranSportId',$carinfo['TranSportId']];
        $data['orderlist'] = HawaList::usergetlist($orderwhere, 'regulatory');
        $data['url'] = WEBURL.'print/contract_rote?p=';
        $data['orderurl'] = WEBURL.'print/orderhawa?id=';
        return myok($data);
    }

    /**
     * 获取企业信息
     * @return [type] [description]
     */
    public function getcompanyinfo(){
        self::is_login();
        $id = input('id');
        if(empty($id)){
            return myerr('缺少参数，请重新尝试');
        }
        $data = Customermodel::user_getinfo($id,'datascreen');
        if(empty($data)){
            return myerr('没有找到此客户');
        }
        if(!empty($data['CompanyId'])){
            $data['contract'] = Contract::getcompanycontractlist($data['CompanyId'],'datascreen_regulatory');

            //获取转移联单
            $orderwhere['where'][] = ['CompanyId',$data['CompanyId']];
            $data['orderlist'] = HawaList::usergetlist($orderwhere, 'regulatory');
            //获取企业档案信息
            $orderwhere['order'] = 'CreateTime desc';
            $data['companyfile'] = CompanyFile::usergetlist($orderwhere, 'regulatory',false);
            //获取产废单位自评信息
            
            //获取产废单位摸排信息
            
        }
        $data['url'] = WEBURL.'print/contract_rote?p=';
        $data['orderurl'] = WEBURL.'print/orderhawa?id=';
        return myok($data);
    }
    

    /**
     * 获取合同详情
     * @return [type] [description]
     */
    public function getcompanyfile(){
        self::is_login();
        $id = input('id');
        if(empty($id)){
            return myerr('缺少参数，请重新尝试');
        }
        $data = CompanyFile::where('Id',$id)->find()->toArray();
        $data['url'] = SERVERURL;
        return myok($data);
    }

    /**
     * 获取合同详情
     * @return [type] [description]
     */
    public function getcontractinfo(){
        self::is_login();
        $id = input('id');
        if(empty($id)){
            return myerr('缺少参数，请重新尝试');
        }
        $data = ContractDetails::where('ContractId',$id)->with('goodinfo')->hidden(['goodinfo'=>['TotalWeight']])->visible(['GoodName','Box','Harmful','Harmful','Usage','EstimatedWeight'])->select()->toArray();
        return myok($data);
    }

    /**
     * 获取行政规划的边界 经纬度点，组成行政区域图
     * @return [type] [description]
     */
    public function getpolygon(){
        // self::is_login();
        $id = input('id');
        if(empty($id)){
            $id = get_config_value('map_city_polygon');
            if(empty($id)){
                return myerr('系统未配置行政区代码');
            }
        }
        $map = new Mapapi;
        $data  = $map->getpolygon($id);
        if($data['code']){
            return myok($data);
        }else{
            return myerr($data);
        }
    }

     /**
     * 大屏登陆逻辑
     * @return boolean [description]
     */
    public static function login()
    {
        $p  = input('screen_password');
        $sb = Setting::login_screen_password($p);
        if (!$sb) {
            moerr('密码错误，请重新尝试');
        }else{
        	return myok('登陆成功');
        }
    }

    /**
     * 大屏检测登陆逻辑
     * @return boolean [description]
     */
    public static function is_login()
    {
        $p  = Request::header('token');
        if(empty($p)){
        	$p = '';
        }
        $sb = Setting::login_screen_password($p);
        if (!$sb) {
            moerr('请输入密码', '', 'relogin');
        }
    }
}
